<template>
  <div class="userStyle">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="formInline" label-width="100px" ref="searchFormRef">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="权益名称" prop="rightsName">
              <el-input v-model="formInline.rightsName" placeholder="请输入权益名称" clearable style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formInline.status" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="12" class="text-align-right">
            <el-button type="primary" @click="getAll" style="margin-right: 10px">查询</el-button>
            <el-button @click="reset" style="margin-right: 10px">重置</el-button>
            <el-button type="success" @click="add">新增权益</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <div class="table-container">
      <el-table :data="tableData" v-loading="tableLoading" style="width: 100%">
        <el-table-column prop="memberName" label="权益名称" />
        <el-table-column prop="memberIcon" label="权益图标">
          <template #default="{ row }">
            <el-image v-if="row.memberIcon" :src="row.memberIcon" class="rights-icon" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column prop="memberReason" label="权益描述" />
        <el-table-column label="创建时间">
          <template #default="{ row }">
            {{ row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间">
          <template #default="{ row }">
            {{ row.updateTime || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <button-table type="edit" @click="edit(row)" />
            <el-popconfirm title="确认删除此权益吗？" @confirm="del(row)">
              <template #reference>
                <button-table type="delete" @click.stop="() => {}" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="formInline.page"
        v-model:page-size="formInline.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="addFormDialog" :title="isChange ? '编辑权益' : '新增权益'" width="600px">
      <el-form :model="addForm" :rules="rules" label-width="120px" ref="formRef">
        <el-row :gutter="20">
          <el-col :xs="24" :lg="12">
            <el-form-item label="权益名称" prop="memberName">
              <el-input v-model="addForm.memberName" placeholder="请输入权益名称" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="12">
            <el-form-item label="权益图标" prop="memberIcon">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="addForm.memberIcon" :src="addForm.memberIcon" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="权益描述" prop="memberReason">
          <el-input
            v-model="addForm.memberReason"
            type="textarea"
            :rows="4"
            placeholder="请输入权益描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addFormDialog = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    getMembership,
    addMembership,
    getMembershipInfo,
    delMembership,
    changeMembership,
    MemberEquityItem
  } from '@/api/memberApi'

  // 表格数据
  const tableData = ref<any[]>([])
  const total = ref(0)
  const tableLoading = ref(false)

  // 搜索表单
  const formInline = ref({
    rightsName: '',
    status: '',
    page: 1,
    pageSize: 10
  })

  // 新增/编辑表单
  const addFormDialog = ref(false)
  const isChange = ref(false) // true-编辑 false-新增
  const addForm = ref<MemberEquityItem>({
    memberId: '',
    memberName: '',
    memberIcon: '',
    memberReason: '',
    memberDesc: ''
  })

  // 表单验证规则
  const rules = ref({
    memberName: [{ required: true, message: '请输入权益名称', trigger: 'blur' }],
    memberIcon: [{ required: true, message: '请上传权益图标', trigger: 'change' }],
    memberReason: [{ required: true, message: '请输入权益描述', trigger: 'blur' }]
  })

  // 上传地址
  const uploadUrl = ref('/api/upload') // 需要替换为实际的上传地址

  // 表单引用
  const formRef = ref<any>()
  const searchFormRef = ref<any>()

  // 处理分页
  const handleSizeChange = (val: number) => {
    formInline.value.pageSize = val
    getAll()
  }

  const handleCurrentChange = (val: number) => {
    formInline.value.page = val
    getAll()
  }

  // 获取所有数据
  const getAll = () => {
    tableLoading.value = true
    // 构造符合后端API要求的参数
    const params = {
      page: formInline.value.page,
      pageSize: formInline.value.pageSize
    }
    getMembership(params)
      .then((res) => {
        // 根据后端返回的数据结构进行适配
        if (res.code === '200') {
          // 根据实际返回的code值调整
          tableData.value = res.data.list || []
          total.value = res.data.total || 0
        } else {
          ElMessage.error(res.message || '获取数据失败')
        }
      })
      .catch((error) => {
        ElMessage.error('获取数据失败: ' + error.message)
      })
      .finally(() => {
        tableLoading.value = false
      })
  }

  // 新增权益
  const add = () => {
    addFormDialog.value = true
    isChange.value = false
    addForm.value = {
      memberId: '',
      memberName: '',
      memberIcon: '',
      memberDesc: ''
    } as MemberEquityItem
  }

  // 编辑权益
  const edit = (row: any) => {
    addFormDialog.value = true
    isChange.value = true
    // 注意：根据后端API调整参数结构
    getMembershipInfo({ memberId: row.memberId })
      .then((res) => {
        if (res.code === '200') {
          // 根据实际返回的code值调整
          addForm.value = res.data || {}
        } else {
          ElMessage.error(res.message || '获取权益信息失败')
        }
      })
      .catch((error) => {
        ElMessage.error('获取权益信息失败: ' + error.message)
      })
  }

  // 删除权益
  const del = async (row: any) => {
    ElMessageBox.confirm('是否继续删除此权益?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        // 注意：根据后端API调整参数结构
        delMembership({ memberId: row.memberId })
          .then((res) => {
            if (res.code === '200') {
              // 根据实际返回的code值调整
              ElMessage({
                type: 'success',
                message: '删除成功!'
              })
              getAll()
            } else {
              ElMessage.error(res.message || '删除失败')
            }
          })
          .catch((error) => {
            ElMessage.error('删除失败: ' + error.message)
          })
      })
      .catch(() => {
        return false
      })
  }

  // 保存表单
  const save = () => {
    formRef.value.validate((valid: boolean) => {
      if (valid) {
        if (!isChange.value) {
          // 新增
          // 构造符合后端要求的数据结构
          const data: MemberEquityItem = {
            memberName: addForm.value.memberName,
            memberIcon: addForm.value.memberIcon,
            memberDesc: addForm.value.memberDesc,
            memberId: ''
          }
          addMembership(data)
            .then((res) => {
              if (res.code === 200) {
                // 根据实际返回的code值调整
                ElMessage({
                  message: '新增成功',
                  type: 'success'
                })
                getAll()
                addFormDialog.value = false
              } else {
                ElMessage.error(res.message || '新增失败')
              }
            })
            .catch((error) => {
              ElMessage.error('新增失败: ' + error.message)
            })
        } else {
          // 编辑
          // 构造符合后端要求的数据结构
          const data: MemberEquityItem = {
            memberId: addForm.value.memberId,
            memberName: addForm.value.memberName,
            memberIcon: addForm.value.memberIcon,
            memberDesc: addForm.value.memberDesc
          }
          changeMembership(data)
            .then((res) => {
              if (res.code === '200') {
                // 根据实际返回的code值调整
                ElMessage({
                  message: '编辑成功',
                  type: 'success'
                })
                getAll()
                addFormDialog.value = false
              } else {
                ElMessage.error(res.message || '编辑失败')
              }
            })
            .catch((error) => {
              ElMessage.error('编辑失败: ' + error.message)
            })
        }
      } else {
        return false
      }
    })
  }

  // 上传图片相关方法
  const handleAvatarSuccess = (response: any, uploadFile: any) => {
    // 需要根据实际的上传接口返回结构调整
    addForm.value.memberIcon = response.data.url
  }

  const beforeAvatarUpload = (rawFile: File) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
      ElMessage.error('图标只能是 JPG/PNG 格式!')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('图标大小不能超过 2MB!')
      return false
    }
    return true
  }

  // 重置
  const reset = () => {
    formInline.value = {
      rightsName: '',
      status: '',
      page: 1,
      pageSize: 10
    }
    getAll()
  }

  onMounted(() => {
    getAll()
  })
</script>

<style lang="scss" scoped>
  .userStyle {
    padding: 20px;
    margin-top: 20px;
    background-color: var(--art-bg-color);
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-container {
    margin-bottom: 20px;
    overflow-x: auto;
    overflow-y: auto;
    touch-action: pan-y;
    -webkit-overflow-scrolling: touch;
  }

  .pagination-wrapper {
    display: flex;
    overflow-x: auto;
    overflow-y: hidden;
    touch-action: pan-x;
    -webkit-overflow-scrolling: touch;
    padding: 10px 0;
    justify-content: flex-start;

    ::v-deep .el-pagination {
      display: flex;
      justify-content: flex-start;
      min-width: auto !important;
      margin: 0 !important;
      padding: 0 10px !important;
    }

    ::v-deep .el-pagination__sizes {
      margin-right: 10px;
    }

    ::v-deep .el-pagination__total {
      margin-right: 10px;
    }

    ::v-deep .el-pagination__jump {
      margin-left: 10px;
    }
  }

  .text-align-right {
    text-align: right;
    
    @media screen and (max-width: 768px) {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      margin-top: 10px;
      
      .el-button {
        margin-bottom: 10px;
      }
    }
  }

  .rights-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }

  .dialog-footer {
    text-align: right;
  }
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: var(--el-text-color-secondary);
    width: 120px;
    height: 120px;
    text-align: center;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
</style>
